//
//  RWNetworkDefines.h
//  RWNetwork
//
//  Created by Ray on 2024/4/25.
//  Copyright © 2024 81SK. All rights reserved.
//

#ifndef RWNetworkDefines_h
#define RWNetworkDefines_h

// --------------- 引入AFNetworking ---------------
#if __has_include(<AFNetworking/AFNetworking.h>)
#import <AFNetworking/AFNetworking.h>
#else
#import "AFNetworking.h"
#endif

#ifdef DEBUG
#define RWNLog(...) NSLog(@"🌐RWNetWork >>> Fun:%s Line:%d\n%@\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#else
#define RWNLog(...)
#endif

#ifndef dispatch_main_async_safe
#define dispatch_main_async_safe(block)\
    if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())) {\
        block();\
    } else {\
        dispatch_async(dispatch_get_main_queue(), block);\
    }
#endif

/// 网络状态
typedef NS_ENUM(NSInteger, RWNetReachabilityStatus) {
    RWNetReachabilityStatusUnknown          = -1,       ///< 未知网络
    RWNetReachabilityStatusNotReachable     = 0,        ///< 无网络
    RWNetReachabilityStatusReachableViaWWAN = 1,        ///< 蜂窝网络
    RWNetReachabilityStatusReachableViaWiFi = 2,        ///< WIFI网络
};

/// 请求操作
typedef NS_ENUM(NSInteger, RWNetOperationType) {
    RWNetOperationNormal,       ///< 普通请求
    RWNetOperationUpload,       ///< 文件上传
    RWNetOperationDownload,     ///< 文件下载
};

/// 请求方式
typedef NS_ENUM(NSInteger, RWNetHTTPMethod){
    RWNetHTTPGET = 0,
    RWNetHTTPPOST,
    RWNetHTTPDELETE,
    RWNetHTTPPUT,
    RWNetHTTPHEAD,
    RWNetHTTPPATCH
};

/// 使用缓存的策略
typedef NS_ENUM(NSInteger, RWCachePolicy){
    RWUndefine = 0,
    RWCallBackTwice = 1,        ///< 数据展示后刷新服务器返回的数据
    RWOnlyLocalCash = 2,        ///< 数据展示后不刷新服务器返回的数据
    RWForceUpdate = 3,          ///< 强制更新只使用服务器返回的最新数据
};

typedef NS_ENUM(NSUInteger, RWNetProcessState) {
    RWNetProcessStateStart = 0,     ///< 开启网络任务HUD状态
    RWNetProcessStateLoading,       ///< 加载中HUD状态
    RWNetProcessStateEnd,           ///< 加载结束HUD状态
    RWNetProcessCancelled = RWNetProcessStateEnd,          ///< 取消网络任务HUD状态
};

/// 数据读取的缓存策略
typedef NS_ENUM(NSInteger, RWNetCacheReadPolicy){
    RWNetCacheReadPolicyOnlyNetwork = 0,    ///< 不读取缓存数据,直接进行请求
    RWNetCacheReadPolicyOnlyCache,          ///< 缓存命中后直接使用.不发起网络请求
    RWNetCacheReadPolicyAlsoNetwork,        ///< 缓存命中后先使用,但仍然发起网络请求
};

/// 数据存储的缓存策略
typedef NS_ENUM(NSUInteger, RWNetCacheWritePolicy) {
    RWNetCacheWritePolicyNone   = 0,        ///< 不保存缓存
    RWNetCacheWritePolicyMemory = 1 << 0,   ///< 内存缓存
    RWNetCacheWritePolicyDisk   = 1 << 1,   ///< 磁盘缓存
    RWNetCacheWritePolicyMemoryAndDisk = RWNetCacheWritePolicyMemory | RWNetCacheWritePolicyDisk    ///< 内存缓存和磁盘缓存
};

/// 网络请求过程状态
typedef NS_ENUM(NSInteger, RWNetErrorCode) {
    RWNetErrorCodeUnknown = 0,          ///< 未知错误.....
    RWNetErrorCodeEmptyData = 204,      ///< 请求成功,但返回的数据为空
    RWNetErrorCodeFormatData = 207,     ///< 请求成功,返回的数据格式不正确
    RWNetErrorCodeParseData = 208,      ///< 请求成功,返回的数据解析错误
    RWNetErrorCodeValidateData = 209,   ///< 请求成功,返回的数据校验失败
    RWNetErrorCodeURLNoExist = 414,     ///< URL不存在
    RWNetErrorCodeNoNetWork = -1009,    ///< 没有网络,网络不通错误
    RWNetErrorCodeCanceled,             ///< 此请求被取消了
};

/// 网络请求返回数据解析格式
typedef NS_ENUM(NSUInteger, RWNetRespDataType) {
    RWNetRespDataSource     = 0,        ///< 源数据格式
    RWNetRespDataJSON       = 1,        ///< JSON格式
    RWNetRespDataXML        = 2,        ///< XML格式
    RWNetRespDataString     = 3,        ///< String格式
};

@class RWNetworkRequest, RWNetworkResponse;

#pragma mark - *****************************************  Block  *********************************************

/// 当前的网络状态
typedef void (^RWNetStatusBlock)(RWNetReachabilityStatus networkStatus);

/// 进度闭包
typedef void(^RWNetProgressBlock)(NSProgress *progress);

/// 请求成功闭包
typedef void(^RWNetSuccessBlock)(RWNetworkResponse *response);

/// 请求失败闭包
typedef void(^RWNetFailureBlock)(RWNetworkResponse *response);

/// 请求取消闭包
typedef void(^RWNetCancelBlock)(RWNetworkResponse *response);

/// 请求失败信息闭包
typedef void(^RWNetFailureInfoBlock)(NSInteger code, NSString *msg);

#pragma mark - *****************************************  Protocol  *********************************************

/**
 * ============================= RWNetworkServer  =======================
 * 请求准备协议, RWNetworkService的派生类必须符合这个协议
 * =========================================================================
 */
@protocol RWNetworkServer <NSObject>
@required

/// 此服务中请求基础URL
- (NSString *)serviceBaseURL;

/// 验证器: 验证服务端返回的数据,response.responseObject一定有值....warning:子线程调用,,return NO;触发错误XYNetErrorCodeDataWrong,执行failure回调. 优先级高于Request同类方法
/// @param response 服务端返回的数据
/// @param request 请求
/// @param errorInfo 验证失败后，用于自定义Code和错误提示
- (BOOL)validateResponse:(RWNetworkResponse *)response forRequest:(RWNetworkRequest *)request errorInfo:(RWNetFailureInfoBlock)errorInfo;

@optional

/// 完整请求路径
- (NSString *)serviceFullURLStringWithPath:(NSString *)urlPath;

/// 此服务中公共请求参数
- (id)serviceParameters:(id)parameters;

/// 此服务中公共请求头参数
- (NSDictionary *)serviceHeaderFileValues:(NSDictionary *)headerFileValues;

- (AFHTTPSessionManager *)sessionManager;
- (AFHTTPRequestSerializer *)requestSerializer;
- (AFHTTPResponseSerializer *)responseSerializer;

@end

/**
 * ============================= RWNetworkRequestIntender  ===========================================
 * 请求准备协议, RWNetworkRequest的派生类必须符合这个协议
 * ==============================================================================================
 */
@protocol RWNetworkRequestIntender <NSObject>
@required

/// 请求所用的服务
- (id<RWNetworkServer>)server;

/// 请求的URL
- (NSString *)requestURL;

/// 请求方式
- (RWNetHTTPMethod)requestMethod;

@optional

/// 请求操作
- (RWNetOperationType)requestOperation;

/// 请求超时时间
- (NSTimeInterval)requestTimeoutInterval;

/// 在请求头中添加的自定义参数
- (NSDictionary *)requestHeadFieldValueDictionary;

/// 请求参数列表
- (id)requestArgument;

/// 公共请求参数列表
- (id)requestCommonArgument;

/// 文件上传数据拼接
- (void)uploadFileWithFormData:(id<AFMultipartFormData>)formData;

/// 断点续传的时候。使用的一个路径
- (NSString *)resumableDownloadPath;

/// 文件下载路径
- (NSString *)downloadPath;

/// 网络请求返回数据解析格式（默认JSON格式）
- (RWNetRespDataType)respDataType;

- (AFHTTPSessionManager *)sessionManager;
- (AFHTTPRequestSerializer *)requestSerializer;
- (AFHTTPResponseSerializer *)responseSerializer;

@end

/**
 * ============================= RWNetworkCompletionDelegate  ===========================================
 * 请求完成后协议
 * ==============================================================================================
 */
@protocol RWNetworkCompletionDelegate <NSObject>
@optional
/// 上传进度
- (void)request:(__kindof RWNetworkRequest *)request uploadProgress:(NSProgress *)progress;

/// 下载进度
- (void)request:(__kindof RWNetworkRequest *)request downloadProgress:(NSProgress *)progress;

/// 请求成功
- (void)request:(__kindof RWNetworkRequest *)request successWithResponse:(RWNetworkResponse *)response;

/// 请求失败
- (void)request:(RWNetworkRequest *)request failureWithResponse:(RWNetworkResponse *)response;

/// 请求被取消
- (void)request:(__kindof RWNetworkRequest *)request cancelledWithResponse:(RWNetworkResponse *)response;
@end

/**
 * ============================= 请求拦截器  ====================================
 * 负责: 检测拦截请求过程
 * ============================================================================
*/
@protocol RWNetworkInterceptor <NSObject>
@optional
- (BOOL)intercept:(RWNetworkRequest *)request shouldCallAPIWithParams:(id)params;
- (void)intercept:(RWNetworkRequest *)request afterCallingAPIWithParams:(id)params;

- (BOOL)intercept:(RWNetworkRequest *)request beforePerformSuccessWithResponse:(RWNetworkResponse *)response;
- (void)intercept:(RWNetworkRequest *)request afterPerformSuccessWithResponse:(RWNetworkResponse *)response;

- (BOOL)intercept:(RWNetworkRequest *)request beforePerformFailWithResponse:(RWNetworkResponse *)response;
- (void)intercept:(RWNetworkRequest *)request afterPerformFailWithResponse:(RWNetworkResponse *)response;

- (void)intercept:(RWNetworkRequest *)request didReceiveResponse:(RWNetworkResponse *)response;

@end

/**
 * ============================= 请求HUD  ====================================
 * 负责: 请求时HUD展示
 * ============================================================================
*/
@protocol RWNetworkShowHUDCaller <NSObject>
@optional
- (void)requestShowHUD:(nonnull RWNetworkRequest *)request process:(RWNetProcessState)state progress:(nullable NSProgress *)progress;
@end


/**
 * ============================= RWNetworkValidator  ===========================================
 * 验证器:主要用于验证外层数据,eg:code,message
 * ==============================================================================================
 */
@protocol RWNetworkValidator <NSObject>
@required

/// 验证器: 验证服务端返回的数据,response.responseObject一定有值....warning:子线程调用,,return NO;触发错误RWNetErrorCodeDataValidateError,执行failure回调. 优先级低于service同类方法
/// @param response 服务端返回的数据
/// @param request 请求
/// @param errorInfo 验证失败后，用于自定义Code和错误提示
- (BOOL)validateResponse:(RWNetworkResponse *)response forRequest:(RWNetworkRequest *)request errorInfo:(RWNetFailureInfoBlock)errorInfo;

@end



#endif /* RWNetworkDefines_h */


